package com.snopy.socket;

import lombok.extern.slf4j.Slf4j;

import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;

/**
 * @author snopy
 * @version 1.0.0
 * @classname SSLSocketClient
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/11 9:47
 */
@Slf4j
public class SSLSocketClient {
    private static String CLIENT_KEY_STORE = "E:/cas_sso.keystore";
    private static String CLIENT_KEY_STORE_PASSWORD = "123456";


    private Socket createNonAuthenticationSocket()throws Exception{
        System.setProperty("javax.net.ssl.trustStore", CLIENT_KEY_STORE);
        SocketFactory sf = SSLSocketFactory.getDefault();
        return sf.createSocket("https://127.0.0.1", 80);
    }

    private Socket createAuthenticationSocket() throws Exception{
        System.setProperty("javax.net.ssl.trustStore", CLIENT_KEY_STORE);
        SSLContext context = SSLContext.getInstance("TLS");
        KeyStore ks = KeyStore.getInstance("jceks");
        ks.load(new FileInputStream(CLIENT_KEY_STORE), null);
        KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");
        kf.init(ks, CLIENT_KEY_STORE_PASSWORD.toCharArray());
        context.init(kf.getKeyManagers(), null, null);

        SocketFactory factory = context.getSocketFactory();
        Socket s = factory.createSocket("127.0.0.1", 80);
        return s;
    }

    private void connect()throws Exception{
       // Socket s = createNonAuthenticationSocket();
     Socket s = createAuthenticationSocket();

        PrintWriter writer = new PrintWriter(s.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        writer.println("hello");
        writer.flush();
        log.info(reader.readLine());
        s.close();
    }


    public static void main(String[] args) throws Exception {
        new SSLSocketClient().connect();
    }

}
